package com.wuheng.smartlock;

import android.app.KeyguardManager;
import android.app.KeyguardManager.KeyguardLock;
import android.app.Service;
import android.app.admin.DevicePolicyManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.IBinder;
import android.os.PowerManager;
import android.util.Log;

public class MyService extends Service {
	private final static String TAG = "Service";
	private SensorManager sensorMgr;
	private Sensor gSensor, pSensor, gyroSensor;
	private float x, y, z;
	private boolean flag = false;
	private DevicePolicyManager policyManager;
	private ComponentName componentName;
	private static boolean isRunning = false;
	private SensorEventListener mGsensorListener;
	private PsensorListener psensorEventListener;
	private GyroListener gyroEventListener;
	private KeyguardLock mLock;
	private ScreenReceiver mReceiver = null;

	static boolean getRunningState() {
		return isRunning;
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO 自动生成的方法存根
		return null;
	}

	@Override
	public void onCreate() {
		// TODO 自动生成的方法存根
		Log.d(TAG, "onCreate");
		super.onCreate();
		mReceiver = new ScreenReceiver();
		gyroEventListener = new GyroListener();
		IntentFilter filter = new IntentFilter();
		filter.addAction(Intent.ACTION_SCREEN_OFF);
		// filter.addAction(Intent.ACTION_SCREEN_ON);
		registerReceiver(mReceiver, filter);
		KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE); // 得到键盘锁管理器对象
		mLock = km.newKeyguardLock("unLock"); // 参数是LogCat里用的Tag
		isRunning = true;
		sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);
		gSensor = sensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
		pSensor = sensorMgr.getDefaultSensor(Sensor.TYPE_PROXIMITY);
		gyroSensor = sensorMgr.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
		psensorEventListener = new PsensorListener();
		mGsensorListener = new SensorEventListener() {
			public void onSensorChanged(SensorEvent e) {
				x = e.values[SensorManager.DATA_X];
				y = e.values[SensorManager.DATA_Y];
				z = e.values[SensorManager.DATA_Z];

				if (Math.abs(y - (-10)) < 1) {
					if (!flag) {
						Log.d(TAG, " haha");
						if (Prefs.isEnable(MyService.this)) {
							if (Prefs.isProximityEnable(MyService.this)) {
								if (((PsensorListener) psensorEventListener)
										.getState()) {
									lockScreen();
									flag = true;
								}
							} else {
								lockScreen();
								flag = true;
							}
						}
					}

				} else if ((y > 2)) {
					if (!flag && Prefs.isWakeEnable(MyService.this)) {
						psensorEventListener.setOk(true);
						if ((((PsensorListener) psensorEventListener)
								.getTapCount() >= 2 && ((PsensorListener) psensorEventListener)
								.getTapCount() < 4)
								|| gyroEventListener.getState()) {
							wakeupScreen();

							// flag = true;
						} else if (Prefs
								.isUnlockEnable(getApplicationContext())
								&& ((PsensorListener) psensorEventListener)
										.getTapCount() >= 4) {
							unlockKey();
							// flag = true;
						}

					}
				} else {
					psensorEventListener.setOk(false);
					flag = false;
				}
			}

			public void onAccuracyChanged(Sensor s, int accuracy) {
			}
		};

		sensorMgr.registerListener(mGsensorListener, gSensor,
				SensorManager.SENSOR_DELAY_NORMAL);
		sensorMgr.registerListener(psensorEventListener, pSensor,
				SensorManager.SENSOR_DELAY_NORMAL);
		sensorMgr.registerListener(gyroEventListener, gyroSensor,
				SensorManager.SENSOR_DELAY_NORMAL);
	}

	private void unlockKey() {

		mLock.disableKeyguard(); // 解锁
		// kl.reenableKeyguard(); //
	}

	private void wakeupScreen() {
		PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);// 获取电源管理器对象
		PowerManager.WakeLock wl = pm.newWakeLock(
				PowerManager.ACQUIRE_CAUSES_WAKEUP
						| PowerManager.SCREEN_DIM_WAKE_LOCK, "bright");
		// 获取PowerManager.WakeLock对象,后面的参数|表示同时传入两个值,最后的是LogCat里用的Tag
		wl.acquire();// 点亮屏幕
		wl.release();// 释放
	}

	private void lockScreen() {
		if (!Prefs.isEnable(this))
			return;
		mLock.reenableKeyguard(); //

		policyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
		Log.d(TAG, "lockScreen");
		// if (policyManager.isAdminActive(componentName)) {// ???????(????????)
		Log.d(TAG, "lockNow");
		policyManager.lockNow();// ????
		// } else {
		// activeManager();// ???????????
		// }
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.i(TAG, "onStartCommand");
		return START_STICKY;
	}

	@Override
	public void onDestroy() {
		Log.i(TAG, "onDestroy");
		isRunning = false;
		sensorMgr.unregisterListener(mGsensorListener);
		sensorMgr.unregisterListener(psensorEventListener);
		sensorMgr.unregisterListener(gyroEventListener);
		unregisterReceiver(mReceiver);
		super.onDestroy();
	}

	public class ScreenReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO 自动生成的方法存根

			// Log.d("wuheng", "onScren ON/OFF");
			if (mLock != null)
				mLock.reenableKeyguard();
		}

	}

}
